package com.ttc.ssm.controller.home;

import com.sun.xml.internal.ws.api.message.ExceptionHasMessage;
import com.ttc.ssm.common.MailPage;
import com.ttc.ssm.controller.admin.CompanyController;
import com.ttc.ssm.controller.common;
import com.ttc.ssm.po.*;
import com.ttc.ssm.service.admin.CompanyService;
import com.ttc.ssm.service.home.HomeCommonService;
import com.ttc.ssm.service.home.HomeCompanyService;
import com.ttc.ssm.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.print.attribute.IntegerSyntax;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * Created by 58296 on 2016/8/8.
 */

@Controller
@RequestMapping("home/company")
public class HomeCompanyController {

    @Autowired
    CompanyService companyService;

    @Autowired
    HomeCompanyService homeCompanyService;

    @Autowired
    HomeCommonService homeCommonService;

    @RequestMapping("changePsd")
    public String changePsd(HttpSession session, Model model) throws Exception
    {
        Integer company_id = (Integer) session.getAttribute("company_id");
        if (company_id <= 0) {
            model.addAttribute("msg","该用户不存在！");
            return "forward:/WEB-INF/jsp/home/login.jsp";
        }

        Company company = new Company();
        company.setCompany_id(company_id);
        company.setPassword(null);
        model.addAttribute("company", company);
        return "home/company/changePsd";
    }

    @RequestMapping("savePsd")
    public String savePsd(Company company, @RequestParam("old_password") String old_password, @RequestParam("confirm_password") String confirm_password,
                          Model model) throws Exception
    {
        if(TextUtils.isEmpty(old_password)){
//            model.addAttribute("customer",customer);
//            model.addAttribute("confirm_password",confirm_password);
//            model.addAttribute("old_password", old_password);
            model.addAttribute("msg",1);
            return "forward:/home/company/changePsd.action";
        }
        if(TextUtils.isEmpty(company.getPassword()) || company.getPassword().length() < 6 || company.getPassword().length()>20){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",2);
            return "forward:/home/company/changePsd.action";
        }
        if(TextUtils.isEmpty(confirm_password)){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",3);
            return "forward:/home/company/changePsd.action";
        }
        if(!company.getPassword().equals(confirm_password)){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",4);
            return "forward:/home/company/changePsd.action";
        }
        Company tmp = companyService.selectCompanyById(company.getCompany_id());
        if(!tmp.getPassword().equals(common.SHA1(tmp.getSalt()+common.SHA1(tmp.getSalt()+common.SHA1(old_password))))){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("msg",5);
            return "forward:/home/company/changePsd.action";
        }

        try{
            company.setSalt(tmp.getSalt());
            int customer_id = homeCompanyService.save_psd(company);
            model.addAttribute("success",1);
            return "forward:/home/company/changePsd.action";
        }catch (Exception e){
//            model.addAttribute("customer",customer);
//            model.addAttribute("old_password", old_password);
//            model.addAttribute("confirm_password",confirm_password);
            model.addAttribute("error",1);
            return "forward:/home/company/changePsd.action";
        }
    }

    @RequestMapping("info_view")
    public String info_view(Model model,HttpSession session,@RequestParam(value = "company_id", defaultValue = "1") int companyId) throws Exception {
        int company_id;
        if(session.getAttribute("company_id")==null||session.getAttribute("company_id").equals("")){
           company_id = companyId;
        }else{
            company_id = (Integer) session.getAttribute("company_id");
        }

        Company company = homeCompanyService.selectCompanyById(company_id);
        model.addAttribute("company",company);
        CompanyDetail companyDetail = homeCompanyService.selectCompanyDetail(company_id);
        model.addAttribute("companyDetail",companyDetail);
        return "home/company/info_view";
    }

    @RequestMapping("info_edit")
    public String info_edit(Model model,HttpSession session) throws Exception {
        int company_id = (Integer) session.getAttribute("company_id");
        Company company = homeCompanyService.selectCompanyById(company_id);
        model.addAttribute("company",company);
        CompanyDetail companyDetail = homeCompanyService.selectCompanyDetail(company_id);
        model.addAttribute("companyDetail",companyDetail);
        List<Zone> zoneList = homeCommonService.getZone();
        model.addAttribute("zoneList",zoneList);
        List<City> cityList = homeCommonService.getCityByZoneId(company.getZone_id());
        model.addAttribute("cityList",cityList);
        List<Industry> industryList = homeCommonService.getIndustry();
        model.addAttribute("industryList",industryList);
        List<CompanyProperty> companyPropertyList = homeCommonService.getCompanyProperty();
        model.addAttribute("companyPropertyList",companyPropertyList);
        List<CompanySize> companySizeList = homeCommonService.getCompanySize();
        model.addAttribute("companySizeList",companySizeList);
        return "home/company/info_edit";
    }

    @RequestMapping("/save_company")
    @ResponseBody
    public int save_company(@RequestBody Company company){
        try{
            if(company.getContact()==null || company.getCity_id() == 0  || company.getContact_sex()==null || company.getZone_num()==null || company.getPhone()==null || company.getTelephone()==null||company.getFullname()==null)
                return -1;
            Date d = new Date();
            company.setDate_modified(d);
            companyService.updateCompany(company);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    @RequestMapping("/save_company_detail")
    @ResponseBody
    public Object save_company_detail(HttpServletRequest request, CompanyDetail companyDetail, @RequestParam(value = "licence_file") MultipartFile temp_pic) throws IOException {
        try{
            if(companyDetail.getMain_industry_id() == 0 ||companyDetail.getSec_industry_id() == 0 ||companyDetail.getCompany_property_id() == 0 ||companyDetail.getCompany_size_id() == 0 || companyDetail.getIndroduce()==null || companyDetail.getRecruit_contact()==null || companyDetail.getZone_num()==null || companyDetail.getPhone()==null || companyDetail.getTelephone()==null)
                return -1;
            String originalFilename = temp_pic.getOriginalFilename();
            CompanyDetail companyDetail1 = companyService.selectCompanyDetail(companyDetail.getCompany_id());
            if(originalFilename.length()>0 && temp_pic !=null && originalFilename !=null) {
                String pic_path=request.getSession().getServletContext().getRealPath("upload/company/");
                String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
                System.out.println(pic_path + newFileName);
                File newFile = new File(pic_path + newFileName);
                temp_pic.transferTo(newFile);
                companyDetail.setLicence_url(newFileName);
                if(companyDetail1!=null && companyDetail1.getLicence_url()!=null)
                    CompanyController.deleteLicence(companyDetail1,request);
            }
            Date d = new Date();
            companyDetail.setDate_modified(d);
            companyDetail.setStatus(0);
            if(companyDetail1!=null)
                companyService.updateCompanyDetail(companyDetail);
            else
                companyService.insertCompanyDetail(companyDetail);
            return 1;
        }catch (Exception e){
            return 0;
        }
    }

    @RequestMapping("mail_box")
    public String mail_box() throws Exception
    {
        return "home/company/mail_box";
    }

    @RequestMapping("/getMailList")
    @ResponseBody
    public Map getMailList(HttpSession session, @RequestParam("p") Integer page, @RequestParam("select") Integer select) throws Exception
    {
        MailPage mailPage = new MailPage();
        mailPage.setPageSize(10);
        mailPage.setCurrentPage(page);
        if (select == 1) {
            mailPage.setIs_read(0);
        }else if (select == 2) {
            mailPage.setIs_read(1);
        }
        int company_id = (Integer) session.getAttribute("company_id");
        System.out.println("================>"+company_id);
        if (company_id > 0) {
            mailPage.setCompany_id(company_id);
        }
        mailPage.setTotalRows(homeCompanyService.countRowsNoReadCompanyDeliveryForMail(mailPage));
        List<DeliveryActivity> deliveryActivities = homeCompanyService.selectDeliveryActivityCompanyForMail(mailPage);

        Map map = new HashMap();
        map.put("data",deliveryActivities);
        map.put("show",mailPage);
        return map;
    }

    @RequestMapping("/getMailList1")
    @ResponseBody
    public Map getMailList1(HttpSession session, @RequestParam("p") Integer page, @RequestParam("select") Integer select) throws Exception
    {
        MailPage mailPage = new MailPage();
        mailPage.setPageSize(10);
        mailPage.setCurrentPage(page);
        if (select == 1) {
            mailPage.setIs_read(0);
        }else if (select == 2) {
            mailPage.setIs_read(1);
        }
        int company_id = (Integer) session.getAttribute("company_id");
        System.out.println("================>"+company_id);
        if (company_id > 0) {
            mailPage.setCompany_id(company_id);
        }
        mailPage.setTotalRows(homeCompanyService.countRowsNoReadCompanyForMail(mailPage));
        List<InviteActivity> inviteActivities = homeCompanyService.selectActivityCompanyForMail(mailPage);

        Map map = new HashMap();
        map.put("data",inviteActivities);
        map.put("show",mailPage);
        return map;
    }

    @RequestMapping("/dealDelivery")
    public String dealDelivery(Integer job_id,Integer id,Integer type){
        try{
            Map data = new HashMap();
            data.put("id", id);
            data.put("is_read", 1);
            if(type == 0) {
                homeCommonService.updateIsRead(data);
            }else {
                homeCommonService.updateIsReadInvite(data);
            }
            return "redirect:/home/resume/resumeManage.action?job_id="+job_id;
        }catch (Exception e){
            return "redirect:/home/company/mail_box.action";
        }
    }

    @RequestMapping("/readInvite")
    @ResponseBody
    public Map readInvite(@RequestParam("id") Integer id) throws Exception
    {
        Map data = new HashMap();
        data.put("id",id);
        data.put("is_read",1);
        try{
            homeCommonService.updateIsReadInvite(data);
            Map map = new HashMap();
            map.put("code",1);
            return map;
        }catch (Exception e){
            e.printStackTrace();
            Map map = new HashMap();
            map.put("code",0);
            return map;
        }
    }

}
